import { onMounted, onUnmounted, ref } from "vue"
// throttle 节流函数，underscore组件库 包含防抖节流等功能
import { throttle } from "underscore"

// 页面滚动到底部时，即可加载数据
export function useScroll(elRef) {
  let el = window
  // 是否滚动到底部
  const isReachBottom = ref(false)

  // 整个窗口的高度，获取的是当前元素可视区的高度
  const clientHeight = ref(0)

  // 可滚动区域的高度，获取的是当前元素上可滚动的高度
  const scrollHeight = ref(0)

  // 向上滚动时，超出窗口区域的高度
  const scrollTop = ref(0)

  const scrollListenHandle = throttle(() => {
    if (el === window) {
      clientHeight.value = document.documentElement.clientHeight
      scrollTop.value = document.documentElement.scrollTop
      scrollHeight.value = document.documentElement.scrollHeight
    } else {
      clientHeight.value = el.clientHeight
      scrollTop.value = el.scrollTop
      scrollHeight.value = el.scrollHeight
    }
    if (clientHeight.value + scrollTop.value + 1 >= scrollHeight.value) {
      console.log("滚动到底部了")
      isReachBottom.value = true
    }
  }, 100)

  // console.log(isReachBottom.value, clientHeight.value, scrollTop.value, scrollHeight.value)
  onMounted(() => {
    if (elRef) el = elRef.value
    el.addEventListener("scroll", scrollListenHandle)
  })
  // 在组件卸载时，取消监听
  onUnmounted(() => {
    el.removeEventListener("scroll", scrollListenHandle)
  })

  return { isReachBottom, clientHeight, scrollTop, scrollHeight }
}
